﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Fleck;
using MyWindowsService.Entity;
using Newtonsoft.Json;

namespace MyWindowsService.Tools
{
    public class WebSocketHelper
    {
        //参考资料：https://www.cnblogs.com/youmingkuang/p/10069363.html
        private static WebSocketHelper _webSocketHelperInstance = null;

        /// <summary>
        /// 获取实例
        /// </summary>
        public static WebSocketHelper GetInstance()
        {
            if (_webSocketHelperInstance == null)
            {
                _webSocketHelperInstance = new WebSocketHelper();
            }

            return _webSocketHelperInstance;
        }

        private List<IWebSocketConnection> _allSockets = new List<IWebSocketConnection>();

        private WebSocketHelper()
        {
            FleckLog.Level = LogLevel.Info;
            var server = new WebSocketServer("ws://0.0.0.0:7181");//任意IP
            server.Start(socket =>
            {
                var str = string.Empty;
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open!");
                    _allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                    _allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    str = message;
                    Console.WriteLine(message);
                    _allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
                };
                socket.OnBinary = file =>
                {

                    var virtualPath = "/Files/";
                    var directory = $"{AppDomain.CurrentDomain.BaseDirectory}{virtualPath}";
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    var path = $"{directory}{DateTime.Now:yyyyMMddHHmmss}{str}";

                    //string path = ("E:/15-烟厂项目/07-Poc/WebSocketDemo/test.txt");
                    //创建一个文件流
                    FileStream fs = new FileStream(path, FileMode.Create);

                    //将byte数组写入文件中
                    fs.Write(file, 0, file.Length);
                    //所有流类型都要关闭流，否则会出现内存泄露问题
                    fs.Close();
                };
            });
        }

        /// <summary>
        /// 发送消息
        /// sign: 0.无数据，1.有数据
        /// </summary>
        public void SendMsg(BaseViewModel msg, int sign = 1)
        {
            foreach (var socket in _allSockets.ToList())
            {
                //要发送的消息与连接的socket一致才发送  
                if (msg.Mark.Equals(socket.ConnectionInfo.Path))
                {
                    var sa = new { Content = msg, Sign = sign,SendTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") };
                    var strJson = JsonConvert.SerializeObject(sa);
                    socket.Send(strJson);
                }
            }
        }
    }
}
